
var express = require('express')
var db = require('../db.js')
var router = express.Router()
var md5 = require('md5-nodejs')
var multer = require('multer');

var bodyParser = require('body-parser')
var urlencodedParser = bodyParser.urlencoded({
    extended: false
})

// 过滤major
router.get('/filterMajor', async function (req, res) {
    var {
        major
    } = req.query
    var sql = `select * from question where majorcid like '${major}'`
    var r = await db.doSQL(sql)
    res.send(db.handerResult(r))
})

// 过滤专业和类型
router.get('/typemajor', async function (req, res) {
    var {
        majorcid,
        typecid
    } = req.query
    var sql = `select * from question`
    if (majorcid) {
        sql += ` where majorcid='${majorcid}'`
    }
    if (typecid) {
        if (majorcid) {
            sql += ` and typecid='${typecid}'`
        } else {
            sql += ` where typecid='${typecid}'`
        }
    }
    var r = await db.doSQL(sql)
    res.send(db.handerResult(r))
})

//随机获取4条数据
router.get('/mode', async function (req, res) {
    let {
        pageSize = 4
    } = req.query
    let sql = `select * from question order by rand() limit ${pageSize}`
    let data = await db.doSQL(sql)
    res.send(db.handerResult(data))
})


//课程获取
router.get('/getQuestions', async function (req, res) {
    var {
        pageSize,
        currentPage,
        keyword,
        sort = "desc",
        orderby = "id"
    } = req.query

    if (!currentPage) {
        currentPage = 0
    }

    if (!pageSize) {
        pageSize = 10
    }
    var sql = `select * from question`
    // var sql = `select m.id,m.name,m.price,m.author,m.typecid,m.inventory,m.author,m.year,m.avatar,m.majorcid,m.Originalprice,m.studyNum from qusetion as m,classify as c , major as a where m.typecid=c.id and m.majorcid=c.id`
    var sql_count = "select count(*) as total from question";

    var num = currentPage * pageSize;
    if (keyword) {
        //根据专业排序
        sql += `   where majorcid like '%${keyword}%'`;
    }
    if (orderby) {
        sql += ` order by ${orderby} ${sort}`;
    }
    sql += ` limit ${num},${pageSize}`
    sql_classify = 'select * from classify'
    const data = await Promise.all([db.doSQL(sql), db.doSQL(sql_count), db.doSQL(sql_classify)])
    res.send(db.handerResult(data[0].data, data[1].data))
})


// 新增题
router.post('/saveQuestions', urlencodedParser, async function (req, res) {
    let {
        name, price, typecid, inventory, author, year, avatar, majorcid, Originalprice, studyNum
    } = req.body
    // console.log(req.body)
    var sql = `insert into question (name, price ,typecid ,inventory ,author ,year ,avatar ,majorcid ,Originalprice ,studyNum) values ('${name}','${price}','${typecid}','${inventory}','${author}','${year}','${avatar}','${majorcid}','${Originalprice}','${studyNum}')`;
    // var sql = "insert into question (name, price) values ('hh','20')"
    // console.log(sql)
    const {
        data
    } = await db.doSQL(sql)
    res.send(db.handerResult(data))
})


//修改题
router.post('/xgQuestions', urlencodedParser, async function (req, res) {
    let {
        id, name, price, typecid, inventory, author, year, avatar, majorcid, Originalprice, studyNum
    } = req.body
    var sql = `update question set name='${name}', price='${price}' , typecid='${typecid}', inventory='${inventory}' ,author='${author}', year='${year}' , avatar='${avatar}', majorcid='${majorcid}',Originalprice='${Originalprice}', studyNum='${studyNum}' where id=${id}`;
    const {
        data
    } = await db.doSQL(sql)
    res.send(db.handerResult(data))
})

//删除题
router.get('/delQuestions', urlencodedParser, async function (req, res) {
    let {
        id
    } = req.query
    var sql = `delete from question where id=${id}`;
    const {
        data
    } = await db.doSQL(sql)
    res.send(db.handerDelete(data))
})

//通过ID找数据
router.get('/getDeail', async function (req, res) {
    var {
        id
    } = req.query
    var sql = `select * from question where id in(${id})`
    var r = await db.doSQL(sql)
    res.send(db.handerResult(r))
})




//图片
var upload = multer({ dest: 'uploads/' })
// 配置diskStorage来控制文件存储的位置以及文件名字等
var storage = multer.diskStorage({
    //确定图片存储的位置
    destination: function (req, file, cb) {
        cb(null, "uploads/")
    },
    //文件名字
    filename: function (req, file, cb) {
        cb(null, "avatar-" + Date.now() + file.originalname)
    }
});


//图片新增
router.post("/addLoad", urlencodedParser, async (req, res) => {
    let { avatar } = req.body
    let sql = `insert into question (avatar) values ('${avatar}')`
    let r = await db.doSQL(sql)
    res.send(db.handerResult(r))
})

//显示图片
router.get('/getUpload', async (req, res) => {
    let { id } = req.query
    let sql = `select u.avatar from question as u where id =${id}`
    let r = await db.doSQL(sql)
    res.send(db.handerResult(r))
})


//生成的专门处理上传的一个工具，可以传入storage、limits等配置
var upload = multer({ storage: storage });

//接收上传图片请求的接口
//图片已经被放入到服务器里,且req也已经被upload中间件给处理好了（加上了file等信息）
router.post('/upload', upload.single('avatar'), function (req, res, next) {
    //线上的也就是服务器中的图片的绝对地址
    var file = req.file.filename
    // console.log(file)
    res.send(db.handerResult({
        filename: file
    }))
});


module.exports = router;